package com.crazyhat.crazyhat.service.impl;

import java.time.LocalDateTime;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crazyhat.crazyhat.attribute.TokenPayloadEnum;
import com.crazyhat.crazyhat.dto.MessageDTO;
import com.crazyhat.crazyhat.entity.Message;
import com.crazyhat.crazyhat.mapper.MessageMapper;
import com.crazyhat.crazyhat.service.IMessageService;
import com.crazyhat.crazyhat.utils.ThreadLocalUtil;
import com.github.yulichang.query.MPJQueryWrapper;

/**
 * <p>
 * 消息 服务实现类
 * </p>
 *
 * @author crazyhat
 * @since 2024-07-05
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public Page<MessageDTO> checkMassages(int pageNum, int pageSize){
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer studentId = (Integer) map.get(TokenPayloadEnum.StudentId.getValue());    

        MPJQueryWrapper<Message> mpjQueryWrapper=new MPJQueryWrapper<>();
        mpjQueryWrapper
            .selectAll(Message.class)
            .select("u.club_name","u.logo_url")
            .leftJoin("club u on u.club_id = t.club_id")
            .eq("t.student_id",studentId)
            .orderByDesc("sent_time");

        Page<MessageDTO> page = new Page<>(pageNum, pageSize);

        Page<MessageDTO> messageList=messageMapper.selectJoinPage(page, MessageDTO.class, mpjQueryWrapper);

        return messageList;
    }

    @Override
    public void sendMessageToStudent(Integer studentId, Integer clubId, String content) {
        Message message = new Message();
        message.setStudentId(studentId);
        message.setClubId(clubId);
        message.setMessageContent(content);
        message.setSentTime(LocalDateTime.now());
        messageMapper.insert(message);
    }
}
